package com.portal.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.portal.pojo.User;
import com.portal.util.HTTPUtil;
import com.sun.deploy.net.HttpUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    public static final String SSO_GET_TICKET="HTTP://47.94.219.203/getTicket";
    public static final String SSO_VERIFY_TICKET="HTTP://47.94.219.203/verifyTicket";
    public static final String SSO_LOGIN="HTTP://47.94.219.203/registor/login.jsp";
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String ticket = (String) httpServletRequest.getAttribute("ticket");
        StringBuffer requestURL = httpServletRequest.getRequestURL();
        if(ticket==null||ticket=="")
        {
            //没有携带ticket，重定向到注册中心，尝试从cookies中获取
            httpServletResponse.sendRedirect(SSO_GET_TICKET+"?backUrl="+requestURL.toString());
        }
        else{
            //进入到这一步，说明已从注册中心重定向回来，并携带了一个ticket
            String jsonString = HTTPUtil.doPostStr(SSO_VERIFY_TICKET, "ticket=" + ticket);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(jsonString);
            String status = (String) jsonObject.get("status");
            User user = (User) jsonObject.get("user");//JSON.toJavaObject((JSON) JSON.parse(jsonString), User.class);
            if(status.equals("success")||user!=null){
                HttpSession session = httpServletRequest.getSession();
                session.setMaxInactiveInterval(600);
                session.setAttribute("user",user);
                return true;
            }
            else{
                // ticket无效 ，重新登录
                httpServletResponse.sendRedirect(SSO_LOGIN);
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
